package com.lfg.leetcode.leetcode100;


public class No174calculateMinimumHP {

    public static void main(String[] args) {
        int[][] dungeon = new int[3][3];
        dungeon[0] = new int[]{-2, -3, 3};
        dungeon[1] = new int[]{-5, -10, 1};
        dungeon[2] = new int[]{10, 30, -5};
        int ret = calculateMinimumHP(dungeon);
        System.out.println(ret);
    }

    public static int calculateMinimumHP(int[][] dungeon) {
        int n = dungeon.length;
        if (0 == n) {
            return 0;
        }
        int m = dungeon[0].length;
        int[][] minHp = new int[n][m];
        if (dungeon[n - 1][m - 1] < 0) {
            minHp[n - 1][m - 1] = -dungeon[n - 1][m - 1] + 1;
        } else {
            minHp[n - 1][m - 1] = 1;
        }
        for (int i = m - 2; i >= 0; i--) {
            minHp[n - 1][i] = Math.max(minHp[n - 1][i + 1] - dungeon[n - 1][i], 1);
        }
        for (int i = n - 2; i >= 0; i--) {
            minHp[i][m - 1] = Math.max(minHp[i + 1][m - 1] - dungeon[i][m - 1], 1);
        }


        for (int i = n - 2; i >= 0; i--) {
            for (int j = m - 2; j >= 0; j--) {
                minHp[i][j] = Math.min(minHp[i + 1][j] - dungeon[i][j], minHp[i][j + 1] - dungeon[i][j]);
                minHp[i][j] = Math.max(1, minHp[i][j]);
            }
        }
        return minHp[0][0];
    }
}
